<?php

class UserRoleManager extends TModule
{
	// -------------------- basic functions --------------------
	public function addUserRole($user_id, $role_id)
	{
		$user_role = $this->getUserRole($user_id, $role_id);
		if($user_role == null)
		{
			$user_role = new UserRoleRecord();
			$user_role->setData($user_id, $role_id);
		
			if($user_role->save())
				return $user_role;
			else
				return null;
		}
		else
			return $user_role;		
	}
	
	public function deleteUserRole($user_id, $role_id)
	{
		$user_role = UserRoleRecord::finder()->deleteAll('user_id = ? AND role_id = ?', $user_id, $role_id);
		if($user_role instanceof UserRoleRecord)
			return $user_role->delete();
		return false;
	}
	
	public function deleteUserRoleByUserId($user_id)
	{
		return UserRoleRecord::finder()->deleteAll('user_id = ?', $user_id);
	}
	
	public function getUserRole($user_id, $role_id)
	{
		return UserRoleRecord::finder()->find('user_id = ? AND role_id = ?', $user_id, $role_id);
	}
	
	// -------------------- extended functions --------------------
	public function getUserRolesListByUserId($user_id, $revert = false, $offset = -1, $limit = -1)
	{
		$criteria = new TActiveRecordCriteria();
		$criteria->Condition = 'user_id = :user_id';
		$criteria->Parameters[':user_id'] = $user_id;
		
		if($revert)
			;//$criteria->OrdersBy['registration'] = 'desc';
			
		if($offset < 0 || $offset == null)
			$offset = 0;
		if($limit < 0 || $limit == null)
			$limit = $this->countUserRoles();
			
		$criteria->Offset = $offset;
		$criteria->Limit = $limit;
		
		return UserRoleRecord::finder()->findAll($criteria);
	}
	
	public function getUserRolesTitlesListByUserId($user_id, $revert = false, $offset = -1, $limit = -1)
	{
		$user_roles = $this->getUserRolesListByUserId($user_id, $revert, $offset, $limit);
		$roles = array();
		foreach($user_roles as $user_role)
		{
			$role_manager = $this->Application->Modules['roles'];
			if(($role = $role_manager->getRoleById($user_role->getRoleId())) !== null)
				$roles[] = $role->getTitle();
		}
		return $roles;
	}
	
	public function getUserRolesListByRoleId($role_id, $revert = false, $offset = -1, $limit = -1)
	{
		$criteria = new TActiveRecordCriteria();
		$criteria->Condition = 'role_id = :role_id';
		$criteria->Parameters[':role_id'] = $role_id;
		
		if($revert)
			;//$criteria->OrdersBy['registration'] = 'desc';
			
		if($offset < 0 || $offset == null)
			$offset = 0;
		if($limit < 0 || $limit == null)
			$limit = $this->countUserRoles();
			
		$criteria->Offset = $offset;
		$criteria->Limit = $limit;
		
		return UserRoleRecord::finder()->findAll($criteria);
	}
	
	public function hasUserRole($user_id, $role_id)
	{
		if($this->getUserRole($user_id, $role_id))
			return true;
		return false;
	}
	
	public function countUserRoles()
	{
		return UserRoleRecord::finder()->count();
	}
}

?>